using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace demowebsocket
{
    public class WebSocketHandler:IWebStocketHandler
    {

        private WebSocketsManager webSocketsManager;
        private ILogger<WebSocketHandler> _logger;
        public WebSocketHandler(
            WebSocketsManager webSocketsManager,
            ILogger<WebSocketHandler> _logger
            )
        {
            this.webSocketsManager = webSocketsManager;
            this._logger = _logger;
        }
        
        public async Task OnClientConnect(WebSocket socket)
        {
            _logger.LogInformation("client connect ...");
            webSocketsManager.AddClient(socket);
        }

        public async Task OnClientClose(WebSocket socket)
        {
          
            webSocketsManager.RemoveClient(socket);

        }

        public async Task ReceiveMessageText(WebSocket socket, int len, byte[] buf)
        {
            var msg = Encoding.UTF8.GetString(buf, 0, len);
            
            _logger.LogInformation(msg);

            await Task.Delay(5000);

           await webSocketsManager.SendMessageToAll(msg,socket);

        }
    }
}